package fastdfs

import (
	"fmt"
	"github.com/astaxie/beego/httplib"
	"os"
	"sync"
)

var fileMapAll = []map[string]string{} //定义全局变量
const FS = "http://tfs.wwy158.com:8080/test/upload"   //go-fastdns 上传地址

func UploadAll(FileArr []string) []map[string]string {
	var wg = sync.WaitGroup{}
	num := len(FileArr)
	wg.Add(num)
	for i := 0; i < num; i++ {
		go upload(FileArr[i], wg.Done) //子协程上传文件
	}
	wg.Wait() //等待子协程执行完毕
	//fmt.Println(fileMapAll)
	return fileMapAll
}

/**
go-fastdns文件上传
src 文件路径
DeferFunc 协程函数 wg.Done 进行数量减1
*/
func upload(src string, DeferFunc func()) {
	defer func() {
		DeferFunc()
	}()
	var obj interface{}
	req := httplib.Post(FS)
	req.PostFile("file", src) //文件路径
	req.Param("output", "json")
	req.Param("scene", "")
	req.Param("path", "")
	req.ToJSON(&obj)
	if obj == nil {
		fmt.Println("上传失败！")
		os.Exit(1)
	}
	res := obj.(map[string]interface{})
	res2 := mapInterfaceToMapString(res)
	fileMap := make(map[string]string)
	for key, value := range res2 {
		switch key {
		case "domain":
			fileMap["domain"] = value
		case "md5":
			fileMap["md5"] = value
		case "mtime":
			fileMap["mtime"] = value
		case "path":
			fileMap["path"] = value
		case "scene":
			fileMap["scene"] = value
		case "size":
			fileMap["size"] = value
		case "url":
			fileMap["url"] = value
		}
	}
	fileMapAll = append(fileMapAll, fileMap) //子协程处理的结果合并到全局变量中
}

// map[string]interface{} 转换成map[string]string
func mapInterfaceToMapString(m map[string]interface{}) map[string]string {
	ret := make(map[string]string, len(m))
	for k, v := range m {
		ret[k] = fmt.Sprint(v)
	}
	return ret
}
